package com.vichat.task.service.impl;

import com.vichat.core.dao.BaseDaoI;
import com.vichat.task.entity.CfgTask;
import com.vichat.task.entity.CfgTaskParam;
import com.vichat.task.entity.TaskLog;
import com.vichat.task.service.ITaskService;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.util.Date;
import java.util.HashMap;
import java.util.List;

/**
 * Created by wangluyin on 2017/1/21.
 */
@Service("taskService")
public class TaskServiceImpl implements ITaskService {

    protected static final Logger logger = LoggerFactory.getLogger(TaskServiceImpl.class);

    @Autowired
    private BaseDaoI<CfgTask> cfgTaskDao;

    @Autowired
    private BaseDaoI<CfgTaskParam> cfgTaskParamDao;


    @Autowired
    private BaseDaoI<TaskLog> taskLogDao;


    @Override
    public List<CfgTask> getCfgTaskByTaskType(String taskType) {
        String hql = "from CfgTask where taskTypeCode = :taskType and status = 'U'";
        HashMap params = new HashMap();
        params.put("taskType",taskType);
        return  cfgTaskDao.find(hql,params);
    }

    @Override
    public CfgTask getCfgTaskById(long taskId) {
        return cfgTaskDao.get(CfgTask.class,taskId);
    }
    @Override
    public List<CfgTaskParam> getCfgTaskParamById(long taskId) {
        String hql = "from CfgTaskParam where cfgTaskId = :cfgTaskId";
        HashMap params = new HashMap();
        params.put("cfgTaskId",taskId);
        return cfgTaskParamDao.find(hql,params);
    }

    @Override
    public long insertTaskLog(TaskLog taskLog) {
        taskLog.setStartTime(new Date());
        taskLogDao.save(taskLog);
        return taskLog.getTaskLogId();
    }

    @Override
    public void updateTaskLog(long taskLogId, String status, String result) {
        String hql = "update TaskLog set status = :status , result = :result, endTime = now() where taskLogId = :taskLogId ";
        HashMap params = new HashMap();
        params.put("status",status);
        params.put("result",result);
        params.put("taskLogId",taskLogId);
        taskLogDao.executeHql(hql,params);
    }

    @Override
    public void updateCfgTask(CfgTask cfgTask) {
        String hql = "update CfgTask set status = :status where cfgTaskId = :cfgTaskId ";
        HashMap params = new HashMap();
        params.put("status",cfgTask.getStatus());
        params.put("cfgTaskId",cfgTask.getCfgTaskId());
        taskLogDao.executeHql(hql,params);
    }
}
